package cn.itcast.controller.cargo;

import cn.itcast.base.BaseController;
import cn.itcast.domain.User;
import cn.itcast.domain.cargo.*;
import cn.itcast.domain.vo.ExportProductVo;
import cn.itcast.domain.vo.ExportResult;
import cn.itcast.domain.vo.ExportVo;
import cn.itcast.service.ContractService;
import cn.itcast.service.ExportProductService;
import cn.itcast.service.ExportService;
import cn.itcast.utils.BeanMapUtils;
import cn.itcast.utils.UtilFuns;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cargo/export")
public class ExportController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    @RequestMapping(name = "pageHelper插件分页查询合同管理模块",value = "/contractList")
    public String contractList(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize){

        ContractExample contractExample = new ContractExample();
        contractExample.setOrderByClause("create_time desc");
        ContractExample.Criteria criteria = contractExample.createCriteria();
        criteria.andCompanyIdEqualTo(company_id);
        criteria.andStateEqualTo(1); //合同已上报的

        PageInfo pb = contractService.findAll(contractExample, pageNum, pageSize);
        request.setAttribute("pb",pb);
        return "cargo/export/export-contractList";
    }




    @RequestMapping(name = "pageHelper插件分页查询报运单",value = "/list")
    public String list(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize){

        ExportExample exportExample = new ExportExample();
        exportExample.setOrderByClause("create_time desc");
        ExportExample.Criteria criteria = exportExample.createCriteria();
        criteria.andCompanyIdEqualTo(company_id);
        PageInfo pb = exportService.findAll(exportExample, pageNum, pageSize);
        request.setAttribute("pb",pb);
        return "cargo/export/export-list";
    }


    @RequestMapping(name = "到报运单生成页面",value = "/toExport")
    //复选框多个值：String[]
    //复选框多个值：String  例如：“1,2”
    public String toExport(String id){

        request.setAttribute("id",id);
        return "cargo/export/export-toExport";
    }



    @RequestMapping(name = "报运单的生成",value = "/edit")
    public String edit(Export export){

        export.setCompanyId(company_id);
        export.setCompanyName(company_name);
        if(UtilFuns.isEmpty(export.getId())){
            //新增
            exportService.save(export);
        }else {
            //修改
            exportService.update(export);
        }

        //到最新报运单页面展示新生成的报运单
        return "redirect:/cargo/export/list.do";
    }



    @RequestMapping(name = "到报运单修改页面回显",value = "/toUpdate")
    public String toUpdate(String id){

       //根据id查询报运单到页面展示
        Export export = exportService.findById(id);
        request.setAttribute("export",export);
        //根据id查询报运单下的货物
        ExportProductExample exportProductExample = new ExportProductExample();
        ExportProductExample.Criteria criteria = exportProductExample.createCriteria();
        criteria.andExportIdEqualTo(id);
        List<ExportProduct> list = exportProductService.findAll(exportProductExample);
        request.setAttribute("eps",list);
        return "cargo/export/export-update";
    }


    @RequestMapping(name = "回显报运单",value = "/toView")
    public String toView(String id){

        //根据id查询报运单到页面展示
        Export export = exportService.findById(id);
        request.setAttribute("export",export);

        return "cargo/export/export-view";
    }


    @RequestMapping(name = "删除报运单",value = "/delete")
    public String delete(String id){

        //根据id删除报运单
        exportService.delete(id);

        return "redirect:/cargo/export/list.do";
    }


    //海关报运
            //条件：导入webservice的依赖
    @RequestMapping(name = "海关报运",value = "/exportE")
    public String exportE(String id){
        //1 先报运
            //1.1 根据报运单的id查询到报运单对象
        Export export = exportService.findById(id);
        //1.2 将报运单的对象数据封装给海关需要的ExportVo对象(报运单数据 报运单货物数据)
        ExportVo exportVo = new ExportVo();
        BeanUtils.copyProperties(export,exportVo);
        exportVo.setExportId(export.getId());
        //1.3 将报运单的货物对象数据给海关需要的ExportProductVo对象
        ExportProductExample exportProductExample = new ExportProductExample();
        ExportProductExample.Criteria criteria = exportProductExample.createCriteria();
        criteria.andExportIdEqualTo(id);
        List<ExportProduct> ExportProductlist = exportProductService.findAll(exportProductExample);

        List list=new ArrayList<ExportProductVo>();
        for (ExportProduct exportProduct : ExportProductlist) {
                //有一个exportProduct对象就得有一个海关需要的exportProductVo对象
            ExportProductVo exportProductVo = new ExportProductVo();
            BeanUtils.copyProperties(exportProduct,exportProductVo);
            exportProductVo.setExportProductId(exportProductVo.getId());
            list.add(exportProductVo);
        }
        //1.4 将封装好的exportProductVo集合给exportVo
        exportVo.setProducts(list);
        //1.5 通过cxf的api实现远程服务的调用
        WebClient webClient = WebClient.create("http://localhost:8080/jk/ws/export/user");
        webClient.post(exportVo);

        //2 结果查询(报运单和货物的报运结果数据)
        WebClient webClient2 = WebClient.create("http://localhost:8080/jk/ws/export/user/"+id);
        ExportResult exportResult = webClient2.get(ExportResult.class);
        // 根据结果修改自己数据
        exportService.updateExportAndExportProduct(exportResult);
        // 到最新页面展示修改后的数据
        return "redirect:/cargo/export/list.do";
    }



    @RequestMapping(name = "pdf生成",value = "/exportPdf")
    public void exportPdf(String id) throws Exception {
        //1 获取报运单
        Export export = exportService.findById(id);
        //2 获取报运单下的货物
        ExportProductExample exportProductExample=new ExportProductExample();
        ExportProductExample.Criteria criteria = exportProductExample.createCriteria();
        criteria.andExportIdEqualTo(id);
        List<ExportProduct> list = exportProductService.findAll(exportProductExample);
        //3 读取模板文件
        String path = session.getServletContext().getRealPath("/pdf/export.jasper");
        FileInputStream is = new FileInputStream(path);
        //4 动态填充数据
                //报运单  export                map填充方式
        Map<String, Object> map = BeanMapUtils.beanToMap(export);
        //货物    List<ExportProduct>   dataSources-list<对象>
        JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(list);
        JasperPrint jasperPrint = JasperFillManager.fillReport(is, map, datasource);
        //5 导出模板生成pdf
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
    }


















    @RequestMapping(name = "pdf生成",value = "/exportPdf6")
    public void exportPdf6(String id) throws Exception {
        //1 读取jasper文件
        String path = session.getServletContext().getRealPath("/pdf/demo04.jasper");
        FileInputStream is = new FileInputStream(path);
        //2 填充动态内容
        //map填充 $p
        //datasources填充 $F
        Map<String,Object> map=new HashMap<>();

        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql:///export_demo", "root", "root");
        JasperPrint jasperPrint = JasperFillManager.fillReport(is,map,connection);

        //3 导出模板生成pdf
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
    }


    @RequestMapping(name = "pdf生成",value = "/exportPdf4")
    public void exportPdf4(String id) throws Exception {
        //1 读取jasper文件
        String path = session.getServletContext().getRealPath("/pdf/demo03.jasper");
        FileInputStream is = new FileInputStream(path);
        //2 填充动态内容
        //map填充 $p
        //datasources填充 $F
        Map<String,Object> map=new HashMap<>();

        List<User> list = new ArrayList<>();
        for(int i=0;i<10;i++){
            User user = new User();
            user.setCompanyName(i+"a");
            user.setDeptName(i+"b");
            user.setEmail(i+"c");
            user.setUserName(i+"d");
            list.add(user);
        }
        JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(list);
        JasperPrint jasperPrint = JasperFillManager.fillReport(is,map,datasource);

        //3 导出模板生成pdf
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
    }




    @RequestMapping(name = "pdf生成",value = "/exportPdf3")
    public void exportPdf3(String id) throws Exception {
         //1 读取jasper文件
        String path = session.getServletContext().getRealPath("/pdf/demo2.jasper");
        FileInputStream is = new FileInputStream(path);
        //2 填充动态内容
                    //map填充 $p
                    //datasources填充 $F
        Map<String,Object> map=new HashMap<>();
        map.put("companyName","传智播客");
        map.put("deptName","java开发部");
        map.put("email","jack@qq.com");
        map.put("userName","杰克");
        JREmptyDataSource dataSource = new JREmptyDataSource();
        JasperPrint jasperPrint = JasperFillManager.fillReport(is,map,dataSource);

        //3 导出模板生成pdf
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
    }






    /*以下内容都是PDF的内容
    *   1 导入依赖
    *   2 导入制作好的模板（用于java代码的填充和导出）
    *   3 使用提供好的依赖API做填充和导出
    *
    * */
    @RequestMapping(name = "pdf生成",value = "/exportPdf2")
    public void exportPdf2(String id) throws Exception {
        //1 读取模板
        String path = session.getServletContext().getRealPath("/pdf/demo01.jasper");
        FileInputStream is = new FileInputStream(path);
        //2 调用api填充
                //参数1：模板文件流
                //都是要填充的内容
                    //参数2：map
        Map map = new HashMap();
        //参数3：DataSources
        JREmptyDataSource jrEmptyDataSource = new JREmptyDataSource();
        JasperPrint jasperPrint = JasperFillManager.fillReport(is,map,jrEmptyDataSource);

        //3 调用api导出
        JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());

    }

















}
